﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Duality;
using Duality.Components;
using Duality.Components.Renderers;
using Duality.Resources;
using OpenTK;
using OpenTK.Input;


namespace PhoenixCrab.Interface
{
    [Serializable]
    public class MouseSelectable : Component, ICmpUpdatable
    {
        public Boolean ActivateMouseOverImageChange { get; set; }
        
        public ContentRef<Scene> ClickToSceneTransition { get; set; }


        public virtual void OnUpdate()
        {
            MouseOverImageChange();
            TransitionCheck();
        }

        private void MouseOverImageChange()
        {
            if (ActivateMouseOverImageChange && IsMouseOver())
            {
                GameObj.ChildByName("MouseOver").GetComponent<SpriteRenderer>().Active = true;
                GameObj.GetComponent<SpriteRenderer>().Active = false;
            }
            else
            {
                GameObj.GetComponent<SpriteRenderer>().Active = true;
                GameObj.ChildByName("MouseOver").GetComponent<SpriteRenderer>().Active = false;
            }
        }


        private void TransitionCheck()
        {
            if (ClickToSceneTransition == null) return;
            if (IsMouseOver() && DualityApp.Mouse.ButtonHit(MouseButton.Left))
            {
                Scene.Current = ClickToSceneTransition.Res;
            }
        }


        private bool IsMouseOver()
        {
            IEnumerable<Camera> cam = Scene.Current.Cameras;
            Rect r = cam.ElementAt(0).SceneOrthoAbs;


            Vector2 v = new Vector2(r.W/2, r.H/2);
            v += GameObj.Transform.Pos.Xy;

            v -= DualityApp.Mouse.Pos;
            return GameObj.GetComponent<SpriteRenderer>().Rect.Contains(v);
        }
    }
}